//
//  GQTabBar.m
//  LotteryProject
//
//  Created by Ezra on 16/5/19.
//  Copyright © 2016年 Ezra. All rights reserved.
//

#import "GQTabBar.h"
#import "GQTabBarButton.h"

@interface GQTabBar()

@property (nonatomic, weak)UIButton *selButton;

@end

@implementation GQTabBar

-(void)setItems:(NSArray *)items
{
    _items = items;
    
    for (int i = 0; i < self.items.count; i++) {
        
        //1.取出对应模型
        UITabBarItem *item = self.items[i];
        
        //2.添加子控件
        UIButton *button = [[GQTabBarButton alloc]init];
        [self addSubview:button];
        
        [button setBackgroundImage:item.image forState:UIControlStateNormal];
        [button setBackgroundImage:item.selectedImage forState:UIControlStateSelected];
        
        //点击事件
        [button addTarget:self action:@selector(buttonOnClick:) forControlEvents:UIControlEventTouchDown];
        
        button.tag = i;
        if (i == 0) {
            [self buttonOnClick:button];
        }
        
    }
    
}
- (void)buttonOnClick:(UIButton *)button
{
    //1.取消上次点击
    self.selButton.selected = NO;
    //2.选中当前按钮
    button.selected = YES;
    //3.记录当前点击
    self.selButton = button;
    
    if ([self.delegate respondsToSelector:@selector(tabBar:index:)]) {
        [self.delegate tabBar:self index:button.tag];
    }
    
}

//layoutsubviews设置尺寸
- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat buttonX = 0;
    CGFloat buttonY = 0;
    CGFloat buttonW = self.frame.size.width / self.subviews.count;
    CGFloat buttonH = self.frame.size.height;
    
    //设置子控件尺寸
    int i = 0;
    for (UIButton *button in self.subviews) {
        
        buttonX = i * buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        i++;
    }
}

@end













